<?php 
	
	function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

	    $ckey_length = 4;
	    $key = md5($key);
	 
	    $keya = md5(substr($key, 0, 16));
	    $keyb = md5(substr($key, 16, 16));
	    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
	    $cryptkey = $keya.md5($keya.$keyc);
	    $key_length = strlen($cryptkey);
	    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	    $string_length = strlen($string);
	    $result = '';
	    $box = range(0, 255);
	    $rndkey = array();
	    for($i = 0; $i <= 255; $i++) {
	        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
	    }
	    for($j = $i = 0; $i < 256; $i++) {
	        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
	        $tmp = $box[$i];
	        $box[$i] = $box[$j];
	        $box[$j] = $tmp;
	    }
	    for($a = $j = $i = 0; $i < $string_length; $i++) {
	        $a = ($a + 1) % 256;
	        $j = ($j + $box[$a]) % 256;
	        $tmp = $box[$a];
	        $box[$a] = $box[$j];
	        $box[$j] = $tmp;
	        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	    }
	    if($operation == 'DECODE') {
	        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
	            return substr($result, 26);
	        } else {
	            return '';
	        }
	    } else {
	        return $keyc.str_replace('=', '', base64_encode($result));
	    }
	}
	
	
	function sendMail($username,$usermail,$title,$content){
		Vendor("phpMailer.mailer");
		$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
		$mail->IsSMTP(); // telling the class to use SMTP
		try {
		  $mail->SMTPDebug  = 1;                     // enables SMTP debug information (for testing)
		  $mail->SMTPAuth   = true;                  // enable SMTP authentication
		  $mail->Host       = C("SYSTEM_MAIL.SMTP_SERVER"); // sets the SMTP server
		  $mail->Port       = C("SYSTEM_MAIL.SMTP_PORT");                    // set the SMTP port for the GMAIL server
		  $mail->Username   = C("SYSTEM_MAIL.SMTP_USERNAME"); // SMTP account username
		  $mail->Password   = C("SYSTEM_MAIL.SMTP_PASSWORD");        // SMTP account password
		  $mail->SetFrom(C("SYSTEM_MAIL.SMTP_USERNAME"), 'SYSTEM');
		  $mail->AddAddress($usermail, $username);
		  $mail->Subject = $title;
		  $mail->MsgHTML($content);
		  return $mail->Send();
		} catch (phpmailerException $e) {
		  echo $e->errorMessage(); //Pretty error messages from PHPMailer
		} catch (Exception $e) {
		  echo $e->getMessage(); //Boring error messages from anything else!
		}
	}
	
	function alertTips($tips) {
		if ($tips) {
			return "<script>setTimeout(function() { alert(\"".$tips."\"); },100);</script>";
		} else {
			return "";
		}
	}
	
	function buildCountry() {
		$_des = M("country")->order("en asc")->select();
		$_ret = '<div class="countryname" id="ct_A" style="display:block">';
		$_ft  = "A";
		$_lang = L('COUNTRY_LANG');
		foreach($_des as $vo) {
			if (substr(strtoupper($vo['en']),0,1) == $_ft) {
				$_ret .= '<div><a href="#" val="'.$vo['en'].'">'.$vo[$_lang].'</a></div>';
			} else {
				$_ft = strtoupper(substr($vo['en'],0,1));
				$_ret .= '</div><div class="countryname" id="ct_'.$_ft.'"><div><a href="#" val="'.$vo['en'].'">'.$vo[$_lang].'</a></div>';
			}
		}
		$_ret .= "</div>";
		return $_ret;
	}
	
	function favStatus($nowuser,$wid) {
		$_v = "";
		if ($nowuser) {
			if (M("userfav")->where(array("userid"=>$nowuser["id"],"favproid"=>$wid))->find()) {
				$_v.= '<a href="javascript:void(0)" class="action_cancel"><div class=" button nofollow marright20">'.L('CANCEL_ACTION').'</div></a>';
				$_v.= '<a href="javascript:void(0)"><div class="follow button now">'.L('FOLLOW_ACTION').'</div></a>';
			} else {
				$_v.= '<a href="javascript:void(0)"  class="action_follow"><div class="follow button marright20">'.L('FOLLOW_ACTION').'</div></a>';
			}
		}
		return $_v;
	}
	
	
	function followStatus($nowuser,$uid) {
		$_v = "";
		if ($nowuser) {
			if ($nowuser["id"] <> $uid) {
				if (M("userfollow")->where(array("userid"=>$nowuser["id"],"followuid"=>$uid))->find()) {
					$_v.= '<a href="javascript:void(0)"><div class="follow button now">'.L('FOLLOW_ACTION').'</div></a>';
					$_v.= '<a href="javascript:void(0)" class="action_cancel"><div class=" button nofollow">'.L('CANCEL_ACTION').'</div></a>';
				} else {
					$_v.= '<a href="javascript:void(0)"  class="action_follow"><div class="follow button">'.L('FOLLOW_ACTION').'</div></a>';
				}
			}
		}
		return $_v;
	}
	
	function xserialize($input,$field) {
		$_arr = unserialize($input);
		return $_arr[$field];
	}
	
	function inputDefault($_val,$_default) {
		return h($_REQUEST[$_val]?$_REQUEST[$_val]:$_default);
	}
	
	function getWorker($project_id,$status) {
		//status 3 -> worker && working
		//status 4 -> worker && closed
		$worker = M("probid")->where(array("pid"=>$project_id,"status"=>$status))
				  ->join("__USER__ on __USER__.id = __PROBID__.uid")
				  ->find();
		if ($worker) {
			return $worker['username'];
		} else {
			return "-";
		}
	}
	
	function countAcq($userid) {
		return M("probid")->where(array("uid"=>$userid,"status"=>array("gt",1)))->count();
	}
	
	function countCase($userid) {
		return M("userdemo")->where(array("userid"=>$userid))->count();
	}
	
	function countBider($project_id) {
		return M("probid")->where(array("pid"=>$project_id))->count();
	}
	
	function getAvatar($user) {
		if ($user['userface']) {
			return "__ROOT__/data/avatars/thumb_".$user['userface'];
		} else {
			return "__ROOT__/themes/images/conpic.png";
		}
	}
	
	function importJS($_files) {
		$_list = explode("|",$_files);
		$_r = ""; 
		$ver = "?ver=".C("FRONTEND_VER");
		foreach($_list as $vo) {
			$_r .= "<script type=\"text/javascript\" src=\"__ROOT__/themes/js/".$vo.$ver."\"></script>\n";
		}
		return $_r;
	}
	
	function importCSS($_files) {
		$_list = explode("|",$_files);
		$_r = "";
		$ver = "?ver=".C("FRONTEND_VER");
		foreach($_list as $vo) {
			$_r .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"__ROOT__/themes/css/".$vo.$ver."\" />\n";
		}
		return $_r;
	}
	
	function checkUser($token){
		$userinfo = $token?$token:cookie('vusertoken');
		if ($userinfo){
			$userid = intval($userinfo['userid']);
			if ($userid>0){
				$user = M('user');
				$data = $user->find($userid);
				if (md5("vsokey_".$data['usertoken']) == $userinfo['userkey']) {
					return $data;
				} else {
					return false;
				}
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	
	function msgcount($pid,$uid) {
		if ($uid) {
			return M("proguestbook")->where(array("pid"=>$pid,"uid"=>$uid))->count();
		} else {
			return M("proguestbook")->where(array("pid"=>$pid))->count();
		}
	}
	
	function mdate($time = NULL) {
	    $text = '';
	    $time = $time === NULL || $time < time() ? time() : intval($time);
	    $t = $time - time(); //时间差 （秒）
	    if ($t == 0)
	        $text = '';
	    elseif ($t < 60)
	        $text = $t . 's'; // 一分钟内
	    elseif ($t < 60 * 60)
	        $text = floor($t / 60) . 'mins'; //一小时内
	    elseif ($t < 60 * 60 * 24)
	        $text = floor($t / (60 * 60)) . 'hours'; // 一天内
	    elseif ($t < 60 * 60 * 24 * 3)
	        $text = floor($time/(60*60*24))."days";
	    elseif ($t < 60 * 60 * 24 * 30)
	        $text = date('m-d', $time);
	    return $text;
	}
?>